package com.jackstraw.tools.utils;

import lombok.Data;

import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * 所在包：com.wenhe.session.util
 * 文件名：
 * 项目：session
 * 功能描述：
 * 修改人：Xlz
 * 修改时间：2020-08-12 15:16
 */
public class ClassUtil {

    public static void main(String[] args) throws Exception {
        List<ClassInfo> classList = getClassList("com.wenhe.session");
        classList.stream().forEach(item -> {
            System.out.println(item.getPackageName() + "   :   " + item.getClassName());
        });
    }

    /**
     * 获取方法列表
     * @param className
     * @return
     * @throws ClassNotFoundException
     */
    public static List<String> getMethodList(String className) throws ClassNotFoundException {
        List<String> list = new ArrayList<>();
        Class<?> clz = Class.forName(className);
        Method[] methods = clz.getDeclaredMethods();
        for (Method method : methods) {
            list.add(method.getName());
        }
        return list;
    }

    /**
     * 获取所有的类
     * @param packageName
     * @return
     * @throws Exception
     */
    public static List<ClassInfo> getClassList(String packageName) throws Exception {
        List<ClassInfo> list = new ArrayList<>();
        ClassLoader loader = ClassLoader.getSystemClassLoader();
        Enumeration<URL> resources = loader.getResources(handlePackageName(packageName));
        while (resources.hasMoreElements()) {
            List<Map<String, String>> mapList = new ArrayList<>();
            URL url = resources.nextElement();
            String filePath = url.getPath().substring(1);
            if (filePath.contains("/classes/"))
                FileUtil.getFileInFolder(filePath, true, mapList);
            for (Map<String, String> fileInfo : mapList) {
                String path = fileInfo.get("filePath");
                String name = fileInfo.get("fileName");
                ClassInfo classInfo = new ClassUtil.ClassInfo();
                classInfo.setPackageName(path.substring(path.indexOf(handlePackageName(packageName)), path.lastIndexOf("/")).replaceAll("/", "."));
                classInfo.setFilePath(path);
                classInfo.setClassName(name.substring(0, name.lastIndexOf(".")));
                list.add(classInfo);
            }
        }
        return list;
    }

    /**
     * 包路径点替换为斜杠
      * @param packageName
     * @return
     */
    public static String handlePackageName (String packageName) {
        String url = packageName.replaceAll("\\.", "/");
        return url;
    }

    @Data
    public static class ClassInfo {

        private String filePath;

        private String packageName;

        private String className;

        private List<String> methods;
    }
}
